import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class EmbeddedVideoPlayer extends StatefulWidget {
  final File videoFile;

  const EmbeddedVideoPlayer({
    super.key,
    required this.videoFile,
  });

  @override
  State<EmbeddedVideoPlayer> createState() => _EmbeddedVideoPlayerState();
}

class _EmbeddedVideoPlayerState extends State<EmbeddedVideoPlayer> {
  MethodChannel? _methodChannel;
  bool _isLoading = true;
  bool _hasError = false;
  String _errorMessage = '';

  @override
  void initState() {
    super.initState();
  }

  void _onPlatformViewCreated(int viewId) {
    _methodChannel = MethodChannel('native_video_player_$viewId');
    _loadVideo();
  }

  Future<void> _loadVideo() async {
    if (_methodChannel == null) return;
    
    setState(() {
      _isLoading = true;
      _hasError = false;
    });

    try {
      print('加载视频: ${widget.videoFile.path}');
      
      // 检查文件是否存在
      if (!await widget.videoFile.exists()) {
        throw '视频文件不存在';
      }

      await _methodChannel!.invokeMethod('loadVideo', {
        'path': widget.videoFile.path,
      });
      
      setState(() {
        _isLoading = false;
      });
      
      print('视频加载成功');
    } catch (e) {
      print('视频加载失败: $e');
      setState(() {
        _isLoading = false;
        _hasError = true;
        _errorMessage = e.toString();
      });
    }
  }

  Future<void> _playPause() async {
    if (_methodChannel == null) return;
    
    try {
      await _methodChannel!.invokeMethod('play');
    } catch (e) {
      print('播放/暂停失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!Platform.isMacOS) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 64, color: Colors.white54),
              SizedBox(height: 16),
              Text('仅支持macOS平台', style: TextStyle(color: Colors.white54)),
            ],
          ),
        ),
      );
    }

    return Container(
      color: Colors.black,
      child: Stack(
        children: [
          // 平台视图
          AppKitView(
            viewType: 'native_video_player_view',
            onPlatformViewCreated: _onPlatformViewCreated,
            creationParams: {
              'videoPath': widget.videoFile.path,
            },
            creationParamsCodec: const StandardMessageCodec(),
          ),
          
          // 加载指示器
          if (_isLoading)
            Container(
              color: Colors.black54,
              child: const Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ),
            ),
          
          // 错误显示
          if (_hasError)
            Container(
              color: Colors.black,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.error_outline,
                      color: Colors.white,
                      size: 64,
                    ),
                    const SizedBox(height: 16),
                    const Text(
                      '视频加载失败',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _errorMessage,
                      style: const TextStyle(color: Colors.white70),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 24),
                    ElevatedButton.icon(
                      onPressed: _loadVideo,
                      icon: const Icon(Icons.refresh),
                      label: const Text('重试'),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}